#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
统一异常处理
"""

from enum import Enum

from fastapi.responses import ORJSONResponse


# 错误类型的枚举, python中的普通枚举不能实现既有code又有message的功能
class ResponseEnum(Enum):
    SUCCESS = {"message": "成功", "code": "00000"}
    SYS_ERROR = {"message": "内部错误", "code": "50000"}
    TOKEN_ERROR = {"message": "Token认证失败", "code": "40002"}
    PASSWORD_ERROR = {"message": "用户名或者密码错误", "code": "40001"}
    AUTHORIZATION_ERROR = {"message": "权限不足", "code": "30001"}
    METHOD_ARGUMENT_ERROR = {"message": "参数不正确", "code": "60001"}

    def get_message(self) -> str:
        return self.value["message"]

    def get_code(self) -> str:
        return self.value["code"]


# 自定义异常
class BusinessException(Exception):
    def __init__(self, response_message_enum: ResponseEnum):
        self.response_message_enum = response_message_enum


# 统一响应
class ApiResponse:
    @staticmethod
    def build_success(
        data: any = None,
    ):
        content = {
            "code": ResponseEnum.SUCCESS.get_code(),
            "message": ResponseEnum.SUCCESS.get_message(),
        }
        if data:
            content["data"] = data
        return ORJSONResponse(content=content, status_code=200)

    @staticmethod
    def build_error(response_enum: ResponseEnum = ResponseEnum.SUCCESS):
        content = {
            "code": response_enum.get_code(),
            "message": response_enum.get_message(),
        }
        return ORJSONResponse(content=content, status_code=200)
